from flask import Blueprint, render_template, jsonify
from exts import mail, db
from flask_mail import Message
from flask import request
import string, random
from models import EmailCaptchaModel

bp = Blueprint("auth", __name__, url_prefix="/auth")


# 注册
@bp.route("/register")
def register():
    # 验证用户提交的邮箱和验证码是否对应且正确
    return render_template("register.html")


# 登录
@bp.route("/login")
def login():
    return render_template("login.html")


# 邮箱验证码
@bp.route("/captcha/email")
def get_mail_captcha():
    '''
    传参方式:
    1. /captcha/email/<email>
    2. /captcha/email?email=xxx@qq.com
    验证码类型： 随机纯数字、纯字母、数字＋字母
    '''
    email = request.args.get("email")
    source = string.digits*4
    captcha = random.sample(source, 4)
    captcha = "".join(captcha)
    message = Message(subject="注册验证码", recipients=[email], body=f"您的验证码是：{captcha}")
    mail.send(message)
    # memcached/redis   redis(高速缓存数据库：优点是 1.可以减轻数据库的压力 2.可以提高查询效率):适合存储验证码
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    # RESTful API
    # {code: 200/400/500, message: "", data: {} }
    return jsonify({"code": 200, "message": "", "data": None})


# 邮箱
@bp.route("/captcha/test")
def mail_test():
    message = Message(subject="邮箱测试", recipients=["2044680446@qq.com"], body="这是一条测试邮件")
    mail.send(message)
    return "邮件发送成功！"
